package fxmedia;

// Import Java JDK Classes
import java.io.BufferedInputStream;
import java.io.FileInputStream;

import fxmedia.ui.OrderButton;

/**
 * @author dca
 */
public class Player {
	/** The library.<br/> */
	private Library library;

	/** Flag for specifying if a song is currently playing or not.<br/> */
	private boolean isPlaying = false;

	/** The thread which executes the playing track.<br/> */
	private Thread playerThread;

	/**
	 * Constructs a player.<br/>
	 */
	public Player() {
		library = new Library();
	} // END constructor

	/**
	 * Constructs a player with a library path.<br/>
	 * @param libraryPath The library path.<br/>
	 */
	public Player(String libraryPath) {
		library = new Library(libraryPath);
	} // END constructor

	/**
	 * Returns the library associated with the player.<br/>
	 * @return library The library.<br/>
	 */
	public Library getLibrary() {
		return library;
	} // END getLibrary

	/**
	 * Returns the isPlaying field.<br/>
	 * @return isPlaying true or false.<br/>
	 */
	public boolean isPlaying() {
		return isPlaying;
	} // END isPlaying

	/**
	 * Stops any currently playing track.<br/>
	 */
	@SuppressWarnings("deprecation")
	public void stop() {
        playerThread.stop();
		isPlaying = false;
	} // END stop

	public void play(final FxMedia app) {
		isPlaying = true;

		// Wrap the playing track in a thread so that the app doesn't hang.
		playerThread = new Thread() {
			@Override
			public void run() {
				do {
					// Update track, artist, album, etc in UI
					final MediaFile mediaFile = app.getLibraryList().getSelectionModel().getSelectedItem();
					app.updateTrackInfo(mediaFile.getId3Info());
					app.updateAlbumArt(mediaFile);

					try {
						// Play current track
						new javazoom.jl.player.advanced.AdvancedPlayer(new BufferedInputStream(new FileInputStream(mediaFile))).play();
					} catch(Exception exc) {
						System.out.printf("ERROR: Error playing track: %s%n", exc.getMessage());
						exc.printStackTrace();
					} // END try/catch

					// Select next track
					boolean shuffling = OrderButton.State.SHUFFLE_TRACKS == app.getOrderTracksButton().getState();
					final int index = app.getLibraryList().getNextTrackIndex(shuffling);
					app.getLibraryList().selectAndScrollTo(index);
				} while(isPlaying);
			} // END run
		}; // END Thread

		playerThread.start();
	} // END play
} // END class Player
